package qr.game;

import qr.core.Player;
import qr.game.rest.RestClient;

import com.unboundid.ldap.sdk.BindResult;
import com.unboundid.ldap.sdk.LDAPConnection;
import com.unboundid.ldap.sdk.LDAPException;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.login_layout);

		Button next = (Button) findViewById(R.id.loginButton);
		next.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				EditText unBox = (EditText) findViewById(R.id.userNameField);
				String username = unBox.getText().toString();

				EditText passBox = (EditText) findViewById(R.id.passwordField);
				String password = passBox.getText().toString();

				if (login(username, password)) {
					SharedPreferences p = 
							LoginActivity.this.getSharedPreferences("qrcode", MODE_MULTI_PROCESS);
					p.edit().putString("username", username).commit();
					RestClient c = new RestClient("129.21.91.97", 8080);
					Player pl = new Player(username);
					c.registerUser(username, pl);
					Intent myIntent = new Intent(view.getContext(),GameActivity.class);
					startActivityForResult(myIntent, 0);
				} else {
					Toast.makeText(LoginActivity.this,
							"Invalid username or password.", Toast.LENGTH_LONG)
							.show();
				}
			}
		});

	}

	public boolean login(String username, String password) {
		try {
			String userDn = "uid=" + username + ",ou=people,dc=rit,dc=edu";
			LDAPConnection connection = new LDAPConnection("ldap.rit.edu", 389);

			BindResult auth = connection.bind(userDn, password);
			return auth.getResultCode().isConnectionUsable();
		} catch (LDAPException e) {
			e.printStackTrace();
			return false;
		}
	}

}
